//
//  MJRefreshStateHeader.swift
//  OC-Swift
//
//  Created by 陆文宇 on 2017/2/14.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import UIKit

class MJRefreshStateHeader: MJRefreshHeader {
    
    var lastUpdatedTimeText: ((Date?) -> String)?
    
    lazy var stateTitles: Dictionary<MJRefreshState, String> = {
        return [:]
    }()
    lazy var stateLabel: UILabel = {
        return UILabel.mj_label()
    }()
    lazy var lastUpdatedTimeLabel: UILabel = {
        return UILabel.mj_label()
    }()
    var currentCalendar: Calendar = Calendar.current
    override var state: MJRefreshComponent.MJRefreshState {
        set {
            if super.state != newValue {
                super.state = newValue
            }
            stateLabel.text = stateTitles[newValue]
            
            // 重新设置key（重新显示时间）
            self.lastUpdatedTimeKey = _lastUpdatedTimeKey!
        }
        
        get {
            return _state
        }
    }
    override var lastUpdatedTimeKey: String {
        set {
            super.lastUpdatedTimeKey = newValue
            
            if lastUpdatedTimeLabel.isHidden {
                return
            }
            
            let lastUpdatedTime: Date? = UserDefaults.standard.object(forKey: newValue) as? Date
            
            if lastUpdatedTimeText != nil {
                lastUpdatedTimeLabel.text = lastUpdatedTimeText!(lastUpdatedTime)
                return
            }
            
            if let lastUpdatedTime = lastUpdatedTime {
                let calendar: Calendar = currentCalendar
                let unitFlags: Set<Calendar.Component> = [.year, .month, .day, .hour, .minute]
                let cmp1: DateComponents = calendar.dateComponents(unitFlags, from: lastUpdatedTime)
                let cmp2: DateComponents = calendar.dateComponents(unitFlags, from: Date())
                
                let formatter: DateFormatter = DateFormatter()
                var isToday = false
                if cmp1.day == cmp2.day {
                    formatter.dateFormat = "HH:mm"
                    isToday = true
                } else if cmp1.year == cmp2.year {
                    formatter.dateFormat = "MM-dd HH:mm"
                } else {
                    formatter.dateFormat = "yyyy-MM-dd HH:mm"
                }
                let time: String = formatter.string(from: lastUpdatedTime)
                
                lastUpdatedTimeLabel.text = "\(Bundle.mj_localizedString(for: MJRefreshHeaderLastTimeText))\(isToday ? Bundle.mj_localizedString(for: MJRefreshHeaderDateTodayText) : "")\(time)"
            } else {
                lastUpdatedTimeLabel.text = "\(Bundle.mj_localizedString(for: MJRefreshHeaderLastTimeText))\(Bundle.mj_localizedString(for: MJRefreshHeaderNoneLastDateText))"
            }
        }
        
        get {
            return _lastUpdatedTimeKey!
        }
    }
    var labelLeftInset: CGFloat?
    override init(refreshingClosure: @escaping MJRefreshComponentRefreshingClosure) {
        super.init(refreshingClosure: refreshingClosure)
        
        addSubview(stateLabel)
        addSubview(lastUpdatedTimeLabel)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setTitle(_ title: String, forState state: MJRefreshState) -> Void {
        stateTitles[state] = title
        stateLabel.text = stateTitles[self.state]
    }
    
    override func prepare() {
        super.prepare()
        
        labelLeftInset = MJRefreshLabelLeftInset
        
        setTitle(Bundle.mj_localizedString(for: MJRefreshHeaderIdleText), forState: .idle)
        setTitle(Bundle.mj_localizedString(for: MJRefreshHeaderPullingText), forState: .pulling)
        setTitle(Bundle.mj_localizedString(for: MJRefreshHeaderRefreshingText), forState: .refreshing)
    }
    
    override func placeSubviews() {
        super.placeSubviews()
        
        if stateLabel.isHidden {
            return
        }
        
        let noConstrainsOnStatusLabel: Bool = stateLabel.constraints.count == 0
        
        if lastUpdatedTimeLabel.isHidden {
            if noConstrainsOnStatusLabel {
                stateLabel.frame = bounds
            }
        } else {
            let stateLabelH: CGFloat = mj_h * 0.5
            if noConstrainsOnStatusLabel {
                stateLabel.mj_x = 0
                stateLabel.mj_y = 0
                stateLabel.mj_w = mj_w
                stateLabel.mj_h = stateLabelH
            }
            
            if lastUpdatedTimeLabel.constraints.count == 0 {
                lastUpdatedTimeLabel.mj_x = 0
                lastUpdatedTimeLabel.mj_y = stateLabelH
                lastUpdatedTimeLabel.mj_w = mj_w
                lastUpdatedTimeLabel.mj_h = mj_h - lastUpdatedTimeLabel.mj_y
            }
        }
    }

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
